package cn.virens.database.serviceimpl.sys;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.virens.database.common.BaseServiceImpl;
import cn.virens.database.mysql.mapper.sys.SysUserMapper;
import cn.virens.database.mysql.model.sys.SysUser;
import cn.virens.database.service.sys.SysUserService;
import cn.virens.exception.APIException;

@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, SysUserMapper> implements SysUserService {

	@Autowired
	public SysUserServiceImpl(SysUserMapper mBaseMapper) {
		super(mBaseMapper);
	}

	@Override
	public int saveUserRole(String account, Integer roleID) {
		return mBaseMapper.saveUserRole(account, roleID);
	}

	@Override
	public SysUser getUser(String account) {
		return mBaseMapper.getUser(account);
	}

	@Override
	public int insert(SysUser record) throws APIException {
		if (StringUtils.isEmpty(record.getPassword())) record.setPassword("123456");

		return super.insert(record);
	}

	@Override
	public int update(SysUser record) throws APIException {
		if (record.getId() != null && record.getId() > 0) {
			return super.update(record);
		} else if (StringUtils.isNotEmpty(record.getAccount())) {
			ExampleWrapper example = new ExampleWrapper();
			example.createCriteria((criteria) -> {
				criteria.andEqualTo("account", record.getAccount());
			});

			record.setId(null);
			record.setAccount(null);
			record.setCreateTime(null);

			return mBaseMapper.updateByExampleSelective(record, example);
		} else {
			return 0;
		}
	}

	@Override
	public int changPassword(String account, String password, String password_again) throws Exception {
		if (StringUtils.isEmpty(account)) throw new Exception("账号不可为空");
		if (StringUtils.isEmpty(password) || StringUtils.isEmpty(password_again)) throw new Exception("新密码/确认密码不可为空");
		if (!password.equals(password_again)) throw new Exception("新密码与确认密码不一致");
		SysUser record = new SysUser();
		record.setAccount(account);
		record.setPassword(password);

		return update(record);
	}

	@Override
	protected List<?> doPageQuery(Map<String, Object> param) throws APIException {
		String name = MapUtils.getString(param, "name", null);
		String account = MapUtils.getString(param, "account", null);
	
		return mBaseMapper.getAll(account, name);
	}

	@Override
	protected Class<SysUser> getGenericSuperclass() {
		return SysUser.class;
	}
}
